<template>
  <div>
    <!-- 定价规则表单 -->
    <el-form
      :model="priceRuleForm"
      :rules="priceRuleFormRules"
      ref="priceRuleFormRef"
      label-width="130px"
    >
      <el-form-item label="统一价" prop="price">
        <el-input
          placeholder="请输入统一价"
          v-model="priceRuleForm.price"
          oninput="value=value.replace(/[^\d.]/g,'')"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="优惠金额" prop="special_price">
        <el-input
          placeholder="客户为会员的优惠金额。不填表示没有优惠"
          v-model="priceRuleForm.special_price"
          oninput="value=value.replace(/[^\d.]/g,'')"
        >
          <template slot="append">元</template>
        </el-input>
      </el-form-item>
      <el-form-item label="定价规则有效期" required>
        <el-col :span="11">
          <el-form-item prop="start_time">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              v-model="priceRuleForm.start_time"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col class="line" :span="2">-</el-col>
        <el-col :span="11">
          <el-form-item prop="end_time">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
              v-model="priceRuleForm.end_time"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="priceRuleForm.remark"
          show-word-limit
          maxlength="500"
        ></el-input>
      </el-form-item>
      <el-form-item label="设置差异价" prop="is_diff">
        <el-switch v-model="priceRuleForm.is_diff"></el-switch>
      </el-form-item>
    </el-form>

    <div v-show="priceRuleForm.is_diff">
      <!-- 差异价规则表 -->
      <el-button icon="el-icon-upload" @click="btachAddDiffRule">
        批量新增差异价规则
      </el-button>
      <el-table
        :data="diffTableData"
        border
        style="width: 100%"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="index" label="序号"> </el-table-column>
        <el-table-column prop="id" label="差异价规则ID" width="100px">
        </el-table-column>
        <el-table-column prop="area" label="地区【ID】">
          <template slot-scope="scope">
            <div
              v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"
            >
              <el-cascader
                :options="options"
                :props="props"
                clearable
                filterable
                :show-all-levels="false"
                v-model="scope.row.area"
                ref="myCascader"
                @change="changeArea(scope.row)"
              ></el-cascader>
            </div>
            <div v-else>
              <!-- <span>{{ scope.row.regionName }}</span> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="diff_price" label="差异标准价">
          <template slot-scope="scope">
            <div
              v-if="(scope.row.id && scope.row.editRowVisible) || !scope.row.id"
            >
              <el-input
                placeholder="请输入"
                v-model="scope.row.diff_price"
                oninput="value=value.replace(/[^\d.]/g,'')"
              >
              </el-input>
            </div>
            <div v-else>
              <span>{{ scope.row.diff_price }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- <el-link
                type="warning"
                @click="scope.row.editRowVisible = true"
                v-show="!scope.row.editRowVisible"
              >
                编辑
              </el-link>
              <el-link
                type="success"
                @click="saveSingleDiffPriceRule(scope.row)"
                v-show="scope.row.editRowVisible"
              >
                保存
              </el-link>
              &nbsp; -->
            <el-link
              type="warning"
              v-show="!scope.row.editRowVisible"
              @click="copyColumn(scope.row)"
            >
              复制
            </el-link>
            &nbsp;
            <el-link type="danger" @click="disable(scope.row.index)">
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>

      <div class="addColumn">
        <el-button type="text" icon="el-icon-plus" @click="addColumnRule">
          增加差异规则
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import regionData from '../../assets/js/regionChoose.js'
export default {
  data() {
    var decimalValid = (rule, value, callback) => {
      value = value + ''
      if (value.indexOf('.') !== -1 && value.split('.').length > 2) {
        // 防止输入多个小数点
        callback(new Error('输入正确格式'))
      } else {
        // 不足补位
        value = Number(value).toFixed(2)
        // this.priceRuleForm.price = value
        this.priceRuleForm[rule.field] = value
        callback()
      }
    }
    return {
      // 定价规则
      priceRuleForm: {
        price: '',
        special_price: '',
        start_time: '',
        end_time: '',
        remark: '',
        is_diff: false,
        diff: []
      },
      priceRuleFormRules: {
        price: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: decimalValid, trigger: 'blur' }
        ],
        special_price: [
          { message: '请输入', trigger: 'blur' },
          { validator: decimalValid, trigger: 'blur' }
        ],
        start_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ],
        end_time: [
          {
            required: true,
            message: '请选择日期',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 差异价规则表
      diffTableData: [],
      options: [],
      props: {
        checkStrictly: true,
        value: 'code',
        label: 'name',
        children: 'childs'
      }
    }
  },
  created() {
    this.getOptions()
  },
  methods: {
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    changeArea(row) {
      // row.regionName = this.$refs.myCascader.getCheckedNodes()[0].label
      // row.area = this.$refs.myCascader.getCheckedNodes()[0].value
      // console.log(this.$refs.myCascader.getCheckedNodes())
    },
    copyColumn(row) {
      var newRow = Object.assign({}, row)
      newRow.id = ''
      newRow.editRowVisible = true
      console.log(newRow)
      this.diffTableData.splice(row.index + 1, 0, newRow)
      // console.log(this.productTable)
    },
    disable(index) {
      this.diffTableData.splice(index, 1)
    },
    addColumnRule() {
      this.diffTableData.push({
        id: '',
        area: '',
        // regionName: '',
        diff_price: '',
        editRowVisible: true
      })
    },
    getOptions() {
      var arr = regionData
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr[i].childs.length; j++) {
          delete arr[i].childs[j].childs
        }
      }
      this.options = arr
    },
    saveSingleDiffPriceRule(row) {
      row.editRowVisible = false
      // console.log(row)
    },
    validateForm() {
      let flag = null
      this.$refs.priceRuleFormRef.validate(async (valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },
    getFinalData() {
      // if (this.priceRuleForm.is_diff && this.diffTableData.length === 0) {
      //   return this.$message.error('请配置差异价规则')
      // }
      var diff = []
      for (let i = 0; i < this.diffTableData.length; i++) {
        const item = {}
        item.area =
          this.diffTableData[i].area[this.diffTableData[i].area.length - 1]
        item.provider_id = 1001
        item.price = this.diffTableData[i].diff_price
        diff.push(item)
      }
      this.priceRuleForm.diff = diff
      this.$emit('showPriceRuleRef', this.priceRuleForm)
    },
    btachAddDiffRule() {
      this.$message.info('功能正在研发中，静侯佳音~')
    },
    // 清空数据
    resetAllData() {
      // 清空校验
      this.$refs.priceRuleFormRef.resetFields()
      this.diffTableData = []
    }
  }
}
</script>
<style lang="less" scoped>
.addColumn {
  margin-top: -16px;
  text-align: center;
  border: 1px solid #eee;
  margin-bottom: 10px;
}
.line {
  text-align: center;
}
</style>
